package com.sdp.flow.controller;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

import org.flowable.engine.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActHiComment;
import com.sdp.flow.db.entity.ActHiTaskinst;
import com.sdp.flow.db.service.IActHiProcinstService;
import com.sdp.flow.db.service.IActHiTaskinstService;
import com.sdp.flow.db.service.IWorkflowService;
import com.sdp.flow.dto.ActHiProcinstView;

/**
 * <p>
 *  流程实例控制器
 * </p>
 *
 * @author qcy
 * @since 2021-06-30
 */
@RestController
@RequestMapping("/flowInstance")
public class FlowInstanceController {

	@Autowired
	private Query query;
	
	@Autowired
	private IActHiProcinstService hiProcinstService;
	
	@Autowired
	private IActHiTaskinstService hiTaskinstService;
	
	@Autowired
    protected HistoryService historyService;
	
	@Autowired
	private IWorkflowService workflowService;
	
	
	@RequestMapping(value="/list")
	public Result<?> list(@RequestBody DataCenter dataCenter) {
		IPage<ActHiProcinstView> pageList = query.viewPage(hiProcinstService, ActHiProcinstView.class, dataCenter, new QueryWrapper<>());
		return Result.ok(pageList);
	}
	
	@RequestMapping(value="/instanceTask")
	public Result<?> instanceTask(@RequestBody DataCenter dataCenter) {
		List<ActHiTaskinst> actHiTaskinstList = query.list(hiTaskinstService, ActHiTaskinst.class, dataCenter);
		if(actHiTaskinstList!=null && actHiTaskinstList.size()>0) {
			
			//查询审批意见信息
			List<ActHiComment> commentList = workflowService.getApprovedOpinionNew(actHiTaskinstList.get(0).getProcInstId());
			
			for(ActHiTaskinst actHiTaskinst : actHiTaskinstList) {
				
				if (commentList != null && commentList.size() > 0) {
					for(ActHiComment actHiComment : commentList) {
						if(actHiTaskinst.getId().equals(actHiComment.getTaskId())) {
							actHiTaskinst.setUserSign(actHiComment.getUserSign());
							actHiTaskinst.setUserAvatar(actHiComment.getUserAvatar());
							actHiTaskinst.setUserName(actHiComment.getUserName());
							actHiTaskinst.setIsPass(actHiComment.getIsPass());
							actHiTaskinst.setOpinion(actHiComment.getMessage());
							actHiTaskinst.setProcessingTime(LocalDateTime.ofInstant(actHiComment.getTime().toInstant(), ZoneId.systemDefault()));
						}
					}
				}
			}
		}
		
		return Result.ok(actHiTaskinstList);
	}
	
	
}
